package com.srwl.mytx.utils;

import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import androidx.fragment.app.FragmentActivity;

import com.srwl.mytx.Constant;
import com.srwl.mytx.R;
import com.srwl.mytx.RetrofitManager;
import com.srwl.mytx.domain.CommonResult;
import com.srwl.mytx.domain.User;
import com.srwl.mytx.parse.UserProfileManager;
import com.srwl.mytx.service.UserService;
import com.srwl.mytx.widget.ConfirmDialog;
import com.srwl.mytx.widget.PayPasswordDialog;
import com.srwl.mytx.widget.RechargeDialogFragment;
import com.srwl.mytx.activity.ChangeActivity;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class PayUtils {
    private static final String TAG = "PayUtils";
    private InteractionListener listener;
    private double amount;
    private Context context;
    private String tips;
    private boolean alwaysShowPayPasswordDialog;//无论支付金额多少，总是显示输入支付对话框

    public PayUtils(double amount, Context context) {
        this.amount = amount;
        this.context = context;
    }

    public PayUtils(double amount, Context context, InteractionListener listener) {
        this.listener = listener;
        this.context = context;
        preparePay(amount);
    }

    public PayUtils(Context context, Double amount, String tips, InteractionListener listener) {
        this.listener = listener;
        this.context = context;
        this.amount = amount;
        this.tips = tips;
        preparePay(amount, tips);
    }

    public PayUtils(Context context, Double amount, String tips, boolean alwaysShowPayPasswordDialog, InteractionListener listener) {
        this.listener = listener;
        this.context = context;
        this.amount = amount;
        this.tips = tips;
        this.alwaysShowPayPasswordDialog = alwaysShowPayPasswordDialog;
        preparePay(amount, tips);
    }


    private void preparePay(double amount) {
        this.amount = amount;
        User myUserInfo = UserProfileManager.getInstance().getLoginUserInfo();
        double deposit = myUserInfo.getDeposit() == null ? 0 : myUserInfo.getDeposit();
        double balance = myUserInfo.getBalance() == null ? 0 : myUserInfo.getBalance();

        if (balance - deposit < amount) {//判断余额是否充足
            balanceNotEnough(context, balance - deposit);
        } else if (myUserInfo.getPayLimit() == Constant.ORIGINAL_PAY_PASSWORD_) {//如果没有支付限额，说明还没有设置 过支付密码，需要先设置
            showSetupPayPasswordDialog(context);
        } else if (amount < myUserInfo.getPayLimit()) {//支付金额小于限额，无须携带支付密码
            listener.onPrepareComplete(null);

        } else {
            PayPasswordDialog payPasswordDialog = new PayPasswordDialog(context);
            payPasswordDialog.setOnConfirmListener(new PayPasswordDialog.OnConfirmListener() {
                @Override
                public void onCommit(String passWord) {
                    listener.onPrepareComplete(passWord);
                }
            });
            payPasswordDialog.show();
        }

    }


    private void preparePay(double amount, String tips) {
        this.amount = amount;
        User myUserInfo = UserProfileManager.getInstance().getLoginUserInfo();
        double deposit = myUserInfo.getDeposit() == null ? 0 : myUserInfo.getDeposit();
        double balance = myUserInfo.getBalance() == null ? 0 : myUserInfo.getBalance();
        if (balance - deposit < amount) {//判断余额是否充足
            balanceNotEnough(context, balance - deposit);
        } else if (myUserInfo.getPayLimit() == Constant.ORIGINAL_PAY_PASSWORD_) {//如果没有支付限额，说明还没有设置 过支付密码，需要先设置
            showSetupPayPasswordDialog(context);
        } else if (!alwaysShowPayPasswordDialog && amount <= myUserInfo.getPayLimit()) {//支付金额小于限额，无须携带支付密码
            listener.onPrepareComplete(null);

        } else {
            PayPasswordDialog payPasswordDialog = new PayPasswordDialog(context, tips, Math.abs(amount));
            payPasswordDialog.setOnConfirmListener(new PayPasswordDialog.OnConfirmListener() {
                @Override
                public void onCommit(String passWord) {
                    listener.onPrepareComplete(passWord);
                }
            });
            payPasswordDialog.show();
        }

    }


    private void balanceNotEnough(final Context context, double balance) {
        ConfirmDialog dialog = new ConfirmDialog(context, "提示", "可用余额：" + Utils.moneyFormat(balance) + "\n余额不足，去充值？", true);
        dialog.setConfirmListener(new ConfirmDialog.ConfirmListener() {
            @Override
            public void confirm() {
                // context.startActivity(new Intent(context, ChangeActivity.class));

                final RechargeDialogFragment rechargeDialogFragment = RechargeDialogFragment.newInstance();
                rechargeDialogFragment.show(((FragmentActivity) context).getSupportFragmentManager(), "recharge");
                rechargeDialogFragment.setOnFragmentInteractionListener(new RechargeDialogFragment.OnFragmentInteractionListener() {
                    @Override
                    public void onRechargeSuccess(Double totalBalance) {

                        UserProfileManager.getInstance().setUserBalance(totalBalance);
                        rechargeDialogFragment.dismiss();
                        if (TextUtils.isEmpty(tips)) {
                            preparePay(amount);
                        } else {
                            preparePay(amount, tips);
                        }
                    }

                    @Override
                    public void showToast(String message) {

                    }
                });


            }
        });
        dialog.show();
    }

    private void showSetupPayPasswordDialog(final Context context) {
        ConfirmDialog confirmDialog = new ConfirmDialog(context, "提示", "还没设置支付密码，现在设置？", true);
        confirmDialog.setConfirmListener(new ConfirmDialog.ConfirmListener() {
            @Override
            public void confirm() {
                // context.startActivity(new Intent(context, ChangeActivity.class));
                setUpPayPassword();

            }
        });
        confirmDialog.show();
    }


    private void setUpPayPassword() {
        PayPasswordDialog dialog = new PayPasswordDialog(context, PayPasswordDialog.TYPE_SET_PAY_PASSWORD);
        dialog.show();
        dialog.setOnSetPasswordListener(new PayPasswordDialog.OnSetPassWordListener() {
            @Override
            public void onCommit(String payPassWord, int payLimit) {

                savePayPassword(payPassWord, payLimit);
            }
        });
    }


    private void savePayPassword(String payPassWord, int excusePassWordLimit) {
        final User user = new User();
        user.setPayLimit(excusePassWordLimit);
        user.setPayPassword(payPassWord);
        RetrofitManager.getInstance().createRequest(UserService.class)
                .setPayPassword(user)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "onResponse: " + response.message());
                            showToast(context.getString(R.string.system_busy));
                            return;
                        }

                        if (result.isError()) {
                            Log.e(TAG, "onResponse: " + result.getMsg());
                            switch (result.getStatus()) {
                                case Constant.SETUP_PAY_PASSWORD_REPEAT:
                                    showToast("已经设置过支付密码了");
                            }
                            return;
                        }
                        Log.d(TAG, "onResponse: 支付密码设置完成");
                        // showToast("支付密码设置完成");
                        UserProfileManager.getInstance().syncLoginUserInfo(user);

                        if (TextUtils.isEmpty(tips)) {
                            preparePay(amount);
                        } else {
                            preparePay(amount, tips);
                        }
                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {

                        showToast(context.getString(R.string.system_busy));
                        Log.e(TAG, "onFailure: " + t.getMessage());
                    }
                });
    }

    private void showToast(String content) {
        Toast.makeText(context, content, Toast.LENGTH_LONG).show();
    }

    public interface InteractionListener {
        void onPrepareComplete(String payPassword);
    }
}
